<template>
  <view class="merchant-foods-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">商品管理</text>
      </view>
      <view class="nav-right">
        <button class="add-btn" @click="addFood">+ 添加</button>
      </view>
    </view>

    <!-- 筛选标签 -->
    <view class="filters">
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'all' }"
        @click="setFilter('all')"
      >全部</view>
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'online' }"
        @click="setFilter('online')"
      >已上架</view>
      <view 
        class="filter-btn" 
        :class="{ active: currentFilter === 'offline' }"
        @click="setFilter('offline')"
      >已下架</view>
    </view>

    <!-- 商品列表 -->
    <view class="foods-list">
      <view 
        class="food-card" 
        v-for="food in filteredFoods" 
        :key="food.id"
      >
        <!-- 商品图片 -->
        <image :src="food.image" class="food-image" mode="aspectFill" />

        <!-- 商品信息 -->
        <view class="food-info">
          <text class="food-name">{{ food.name }}</text>
          
          <view class="food-meta">
            <text class="food-price">¥{{ food.price }}</text>
            <text class="food-original-price" v-if="food.originalPrice">¥{{ food.originalPrice }}</text>
          </view>

          <view class="food-stats">
            <text class="stat-item">库存: {{ food.stock }}</text>
            <text class="stat-item">已售: {{ food.soldCount }}</text>
          </view>

          <view class="food-tags">
            <text class="tag" :class="food.status === 1 ? 'online' : 'offline'">
              {{ food.status === 1 ? '已上架' : '已下架' }}
            </text>
            <text class="tag hot" v-if="food.isHot">热门</text>
            <text class="tag recommend" v-if="food.isRecommended">推荐</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="food-actions">
          <button class="action-btn edit" @click.stop="editFood(food)">编辑</button>
          <button class="action-btn delete" @click.stop="deleteFood(food)">删除</button>
          <button 
            class="action-btn toggle" 
            :class="food.status === 1 ? 'offline-btn' : 'online-btn'"
            @click.stop="toggleStatus(food)"
          >
            {{ food.status === 1 ? '下架' : '上架' }}
          </button>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredFoods.length === 0 && !loading">
        <text class="empty-icon">🍱</text>
        <text class="empty-text">暂无{{ getFilterName() }}商品</text>
      </view>

      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <text>加载中...</text>
      </view>
    </view>

    <!-- 底部导航 -->
    <view class="bottom-nav">
      <view class="nav-item" @click="goToHome">
        <text class="nav-icon">🏠</text>
        <text class="nav-label">首页</text>
      </view>
      <view class="nav-item" @click="goToOrders">
        <text class="nav-icon">📋</text>
        <text class="nav-label">订单</text>
      </view>
      <view class="nav-item active">
        <text class="nav-icon">🍱</text>
        <text class="nav-label">商品</text>
      </view>
      <view class="nav-item" @click="goToSettings">
        <text class="nav-icon">⚙️</text>
        <text class="nav-label">设置</text>
      </view>
    </view>
    
    <!-- 自定义弹窗 -->
    <CustomModal ref="customModal" />
  </view>
</template>

<script>
import merchantService from '../../../services/merchant.js'
import { backToMerchantHome } from '../../../utils/navigation.js'
import CustomModal from '../../../components/CustomModal.vue'

export default {
  components: {
    CustomModal
  },
  data() {
    return {
      statusBarHeight: 0,
      currentFilter: 'all',
      loading: false,
      foods: []
    }
  },
  computed: {
    filteredFoods() {
      if (this.currentFilter === 'all') {
        return this.foods
      } else if (this.currentFilter === 'online') {
        return this.foods.filter(food => food.status === 1)
      } else if (this.currentFilter === 'offline') {
        return this.foods.filter(food => food.status === 0)
      }
      return this.foods
    }
  },
  onLoad() {
    this.getStatusBarHeight()
    this.loadFoods()
  },
  onShow() {
    // 从编辑页返回时刷新列表
    this.loadFoods()
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },

    // 加载商品列表
    async loadFoods() {
      this.loading = true
      try {
        const params = {}
        
        // 如果有筛选条件，添加到参数中
        if (this.currentFilter === 'online') {
          params.status = 1
        } else if (this.currentFilter === 'offline') {
          params.status = 0
        }
        
        const response = await merchantService.getFoods(params)
        
        // 后端返回的是数组
        this.foods = response.data || []
        
        console.log('商品列表:', this.foods)
      } catch (error) {
        console.error('加载商品失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        this.foods = []
      } finally {
        this.loading = false
      }
    },

    // 切换筛选
    setFilter(filter) {
      this.currentFilter = filter
      this.loadFoods()
    },

    // 获取筛选名称
    getFilterName() {
      const nameMap = {
        'all': '',
        'online': '已上架',
        'offline': '已下架'
      }
      return nameMap[this.currentFilter] || ''
    },

    // 添加商品
    addFood() {
      uni.navigateTo({
        url: '/pages/merchant/food-edit/food-edit?mode=add'
      })
    },

    // 编辑商品
    editFood(food) {
      uni.navigateTo({
        url: `/pages/merchant/food-edit/food-edit?mode=edit&id=${food.id}`
      })
    },

    // 删除商品
    async deleteFood(food) {
      this.$refs.customModal.show({
        type: 'danger',
        title: '确认删除',
        content: `确定要删除商品"${food.name}"吗？此操作不可恢复！`,
        confirmText: '确认删除',
        cancelText: '取消',
        onConfirm: async () => {
            try {
              await merchantService.deleteFood(food.id)
              
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              })

              // 重新加载商品列表
              setTimeout(() => {
                this.loadFoods()
              }, 500)
            } catch (error) {
              console.error('删除商品失败:', error)
              uni.showToast({
                title: error.message || '删除失败',
                icon: 'none'
              })
            }
        }
      })
    },

    // 切换上下架状态
    async toggleStatus(food) {
      const newStatus = food.status === 1 ? 0 : 1
      const actionText = newStatus === 1 ? '上架' : '下架'
      
      this.$refs.customModal.show({
        type: 'confirm',
        title: `确认${actionText}`,
        content: `确定要${actionText}商品"${food.name}"吗？`,
        confirmText: `确认${actionText}`,
        cancelText: '取消',
        onConfirm: async () => {
            try {
              await merchantService.updateFoodStatus(food.id, newStatus)
              
              uni.showToast({
                title: `${actionText}成功`,
                icon: 'success'
              })
              
              // 刷新商品列表
              setTimeout(() => {
                this.loadFoods()
              }, 500)
            } catch (error) {
              uni.showToast({
                title: `${actionText}失败`,
                icon: 'none'
              })
            }
        }
      })
    },

    // 返回
    goBack() {
      backToMerchantHome()
    },

    // 导航
    goToHome() {
      uni.navigateTo({
        url: '/pages/merchant/home/home'
      })
    },

    goToOrders() {
      uni.navigateTo({
        url: '/pages/merchant/orders/orders'
      })
    },

    goToSettings() {
      uni.navigateTo({
        url: '/pages/merchant/settings/settings'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.merchant-foods-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 140rpx;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

// 顶部导航栏
.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  align-items: center;
  z-index: 998;
}

.nav-left {
  position: absolute;
  left: 0;
  width: 88rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
}

.nav-right {
  position: absolute;
  right: 20rpx;
}

.add-btn {
  height: 56rpx;
  padding: 0 20rpx;
  background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
  color: #fff;
  border: none;
  border-radius: 28rpx;
  font-size: 24rpx;
  line-height: 56rpx;
}

// 筛选标签
.filters {
  position: fixed;
  top: calc(var(--status-bar-height) + 88rpx);
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx;
  display: flex;
  gap: 16rpx;
  z-index: 997;
  border-bottom: 1rpx solid #eee;
}

.filter-btn {
  flex: 1;
  padding: 12rpx 0;
  border-radius: 32rpx;
  border: 2rpx solid #ddd;
  font-size: 24rpx;
  color: #666;
  background: #fff;
  text-align: center;
  
  &.active {
    background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
    border-color: transparent;
    color: #fff;
  }
}

// 商品列表
.foods-list {
  margin-top: calc(var(--status-bar-height) + 88rpx + 100rpx);
  padding: 20rpx;
}

.food-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  gap: 20rpx;
}

.food-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  flex-shrink: 0;
  background: #f0f0f0;
}

.food-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.food-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.food-meta {
  display: flex;
  align-items: baseline;
  gap: 12rpx;
  margin-bottom: 8rpx;
}

.food-price {
  font-size: 32rpx;
  font-weight: 700;
  color: #ff4757;
}

.food-original-price {
  font-size: 22rpx;
  color: #999;
  text-decoration: line-through;
}

.food-stats {
  display: flex;
  gap: 24rpx;
  margin-bottom: 8rpx;
}

.stat-item {
  font-size: 22rpx;
  color: #666;
}

.food-tags {
  display: flex;
  gap: 8rpx;
  flex-wrap: wrap;
}

.tag {
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
  
  &.online {
    background: #e8f5e9;
    color: #4caf50;
  }
  
  &.offline {
    background: #f5f5f5;
    color: #999;
  }
  
  &.hot {
    background: #ffebee;
    color: #f44336;
  }
  
  &.recommend {
    background: #e3f2fd;
    color: #2196f3;
  }
}

.food-actions {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  justify-content: center;
}

.action-btn {
  width: 120rpx;
  height: 56rpx;
  border-radius: 28rpx;
  font-size: 24rpx;
  border: none;
  
  &.edit {
    background: #fff;
    color: #333;
    border: 2rpx solid #ddd;
  }
  
  &.delete {
    background: #fff;
    color: #ff6b6b;
    border: 2rpx solid #ffdddd;
  }
  
  &.toggle {
    color: #fff;
    
    &.online-btn {
      background: linear-gradient(135deg, #4caf50 0%, #66bb6a 100%);
    }
    
    &.offline-btn {
      background: linear-gradient(135deg, #f44336 0%, #e57373 100%);
    }
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 120rpx 0;
}

.empty-icon {
  display: block;
  font-size: 100rpx;
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

// 加载状态
.loading-state {
  text-align: center;
  padding: 60rpx 0;
  font-size: 28rpx;
  color: #999;
}

// 底部导航
.bottom-nav {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 120rpx;
  background: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding-bottom: env(safe-area-inset-bottom);
}

.nav-item {
  text-align: center;
  
  &.active {
    .nav-icon {
      font-size: 44rpx;
    }
    .nav-label {
      color: #ff8a00;
      font-weight: 600;
    }
  }
}

.nav-icon {
  display: block;
  font-size: 40rpx;
  margin-bottom: 6rpx;
}

.nav-label {
  display: block;
  font-size: 22rpx;
  color: #666;
}
</style>
